// OrderCancelConsumer.java
package edu.del.springbootredisbusinesspractice.consumer;

import edu.del.springbootredisbusinesspractice.commons.config.RabbitMQConfig;
import edu.del.springbootredisbusinesspractice.pojo.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import com.rabbitmq.client.Channel;

import java.io.IOException;

@Slf4j
@Service
public class OrderCancelConsumer {

    @RabbitListener(
            queues = RabbitMQConfig.ORDER_CANCEL_QUEUE,
            containerFactory = "jsonRabbitListenerContainerFactory"
    )
    public void handleCancelOrder(
            @Payload Orders order,
            Channel channel,
            @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {

        try {
            log.info("【取消订单消费】开始处理取消订单，orderNo: {}", order.getOrderNo());

            // TODO: 添加实际业务，如通知用户、退款、物流取消等

            log.info("【取消订单消费】订单取消后续处理完成，orderNo: {}", order.getOrderNo());

            channel.basicAck(deliveryTag, false);

        } catch (Exception e) {
            log.error("【取消订单消费】处理异常，orderNo: {}", order.getOrderNo(), e);
            try {
                channel.basicNack(deliveryTag, false, false);
            } catch (IOException ex) {
                log.error("【取消订单消费】Nack失败", ex);
            }
        }
    }
}